package com.jse;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;

public class Tryer {
	
	private final static ExecutorService executor=Executors.newFixedThreadPool(2);
	private int max=1;//重试次数
	private boolean repty;//是否重试
	private Predicate<Object> res;//结果重试
	private Predicate<Exception> err;//异常重试
	
	public Tryer() {}
	public Tryer retry(boolean repty) {
		this.repty=repty;
		return this;
	}
	public Tryer res(Predicate<Object> repty) {
		this.res=repty;
		return this;
	}
	public Tryer err(Predicate<Exception> repty) {
		this.err=repty;
		return this;
	}
	public Tryer max(int max) {
		this.max=max;
		return this;
	}
	
	public Object get(Callable<?> callable) {
		Future<?> future=null;
		Object obj=null;
		for (int i = 0; i < max; i++) {
		try {
			future=executor.submit(callable);
			obj=future.get();
				if(res!=null&&res.test(obj)) {//结果重试器
					continue;
				}
		} catch (Exception e) {
				if(err!=null&&err.test(e)) {//异常重试器
					continue;
				}
				if(future!=null)
			future.cancel(true);
		}
		if(!repty)
		break;
		}
		return obj;
	}
	

	public static void main(String[] args) {
		new com.jse.Tryer().max(3)
		.res((o)->{
			return o!=null;
		})
		.err((e)->{
			System.err.println("异常消息:"+e.getMessage());
			return true;
		})
		.get(()->{
			System.out.println("执行逻辑"+Thread.currentThread().getName());
			return null;
		});
	}

}
